package com.wk.unittestshow;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;


public class CalcMD5 {
    private static final char[] hexCode = "0123456789ABCDEF".toCharArray();
    public static void main(String[] args) {
        Map<String ,Md5SaveBean> md5Info = new HashMap<>() ;

        String path ="F:\\temp_test\\test\\片假读音" ;
        getAllFiles(path ,md5Info) ;

        for (Object object : md5Info.keySet()) {
            String key = (String) object;
            Md5SaveBean bean =   md5Info.get(key);
            if(bean.count>1){
                System.out.println("\r\n发现重复文件-> "+ key +"  "+ bean.count+"   "+bean.name);
            }
        }
    }

    /**
     * 计算文件 MD5
     * @return 返回文件的md5字符串，如果计算过程中任务的状态变为取消或暂停，返回null，
     * 如果有其他异常，返回空字符串
     */
    private static String calcMD5(File file) {
        try (InputStream stream = Files.newInputStream(file.toPath(), StandardOpenOption.READ)) {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] buf = new byte[8192];
            int len;
            while ((len = stream.read(buf)) > 0) {
                digest.update(buf, 0, len);
            }
            return toHexString(digest.digest());
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }

    private static String toHexString(byte[] data) {
        StringBuilder r = new StringBuilder(data.length * 2);
        for (byte b : data) {
            r.append(hexCode[(b >> 4) & 0xF]);
            r.append(hexCode[(b & 0xF)]);
        }
        return r.toString();
    }

    private static void getAllFiles(String strPath ,Map<String ,Md5SaveBean> md5Info) {
        File dir = new File(strPath);
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    getAllFiles(file.getAbsolutePath() ,md5Info);
                } else {
                    // 文件
                    String md5 = calcMD5(file);
                    boolean hasContain = md5Info.containsKey(md5) ;
                    if(hasContain){
                        Md5SaveBean bean = md5Info.get(md5) ;
                        bean.count =bean.count+1 ;
                        bean.name=bean.name +"\r\n"+file.getAbsolutePath();
                        md5Info.put( md5 , bean ) ;
                    }else{
                        md5Info.put( md5 , new Md5SaveBean("\r\n"+file.getAbsolutePath() ,1) ) ;
                    }
                }
            }
        }
    }



}